from typing import List
from gui.wechat_gui import WechatGui

from myutils.window_helper import *
from model.exception import (
    ParkTokenFatalError,
    ParkTokenTokenParseError,
    ParkTokenWechatHwndError,
)
from model.token import Token, TokenType
import re
import json
from datetime import datetime
import myutils.services_helper as services_helper
import uuid


class YdtGui(WechatGui):
    def __init__(self):
        super().__init__()
        self.wechat_hwnd_list = []

    def set_fiddler_hwnd(self, hwnd):
        self.fiddler_hwnd = hwnd

    def set_wechat_hwnd_list(self, hwnd_list):
        self.wechat_hwnd_list = hwnd_list

    def check_env(self):
        # super().check_env()
        if not self.fiddler_hwnd:
            raise ParkTokenFatalError("未找到fiddler窗口")

    def extract_tokens(self, fiddle_text) -> List[Token]:
        """使用正则提取token与openid"""

        pattern = r"\?token=(\w+)&parkId=&operatorId=&coopkey=&code=(\w+)"

        r = re.findall(pattern, fiddle_text)

        tokens = []

        for r_token, r_code in r:
            token = Token()
            token.userid = r_code
            token.data = json.dumps(
                {
                    "token": r_token,
                    "auth_code": r_code,
                    "updateTime": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                },
                ensure_ascii=False,
            )
            token.type = TokenType.Ydt
            tokens.append(token)
        return tokens

    def start(self):
        self.check_env()
        show_window(self.fiddler_hwnd, "max")
        self.hotkey("ctrl", "x")
        while True:
            self.close_wechat_browser()
            for hwnd in self.wechat_hwnd_list:
                for i in range(3):
                    show_window(hwnd, "max")
                    time.sleep(0.1)
                    self.click_image("./images/ydt/logo.png")
            show_window(self.fiddler_hwnd, "max")
            self.click_image("./images/ydt/fiddler_row.png")
            self.hotkey("ctrl", "a")
            self.hotkey("ctrl", "shift", "s")
            time.sleep(0.5)
            services_helper.save_token(self.extract_tokens(get_clipboard_text()))
            self.hotkey("del")
            self.hotkey("space")
